package com.ctlele.team.space.fragment.impl;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.ctlele.team.space.R;
import com.ctlele.team.space.activity.BaseActivity;
import com.ctlele.team.space.adapter.FriendItemAdapter;
import com.ctlele.team.space.api.Api;
import com.ctlele.team.space.api.ApiStatusCode;
import com.ctlele.team.space.api.Apis;
import com.ctlele.team.space.entity.vo.ChatMessageVo;
import com.ctlele.team.space.entity.vo.FriendItemVo;
import com.ctlele.team.space.entity.vo.UserVo;
import com.ctlele.team.space.entity.vo.resp.FriendListResp;
import com.ctlele.team.space.entity.vo.resp.UserInfoResp;
import com.ctlele.team.space.fragment.BaseFragment;
import com.ctlele.team.space.util.MessageUtils;
import com.ctlele.team.space.util.UserContext;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class FriendListFragment extends BaseFragment {

    private static final String TAG = "FriendListFragment";

    private RecyclerView mRecyclerView;

    private SmartRefreshLayout mSmartRefreshLayout;

    private FriendItemAdapter mAdapter;

    private FriendListFragment() {
    }

    public static FriendListFragment createFriendList() {
        return new FriendListFragment();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_friend_list;
    }

    @Override
    protected void initView() {
        mRecyclerView = mRootView.findViewById(R.id.friend_list);
        mSmartRefreshLayout = mRootView.findViewById(R.id.refresh_layout);
        mAdapter = new FriendItemAdapter((BaseActivity) getActivity());
    }

    @Override
    protected void initData() {
        mRecyclerView.setAdapter(mAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mSmartRefreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        mSmartRefreshLayout.setOnRefreshListener((refresher) -> getFriendList());

        getFriendList();

        Api.get(getContext(), Apis.LOGIN_USER_INFO, new ArrayList<>(), new Api.ApiCallback() {
            @Override
            public void onFailure(Context context, Call call, IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }

            @Override
            public void onResponse(Context context, Call call, Response response) throws IOException {
                String res = response.body().string();
                UserInfoResp resp = JSON.parseObject(res, UserInfoResp.class);
                if (resp != null && resp.getCode().equals(ApiStatusCode.OK)) {
                    UserVo userVo = resp.getData();
                    UserContext.set(userVo);
                }
            }
        });

        // 聊天消息的接收和推送
        Api.newWebSocket(Apis.CHAT_MSG_PUSH, new WebSocketListener() {
            @Override
            public void onClosed(@NonNull WebSocket webSocket, int code, @NonNull String reason) {
                super.onClosed(webSocket, code, reason);
            }

            @Override
            public void onFailure(@NonNull WebSocket webSocket, @NonNull Throwable t, @Nullable Response response) {
                super.onFailure(webSocket, t, response);
            }

            @Override
            public void onMessage(@NonNull WebSocket webSocket, @NonNull String text) {
                super.onMessage(webSocket, text);
                ChatMessageVo message = JSON.parseObject(text, ChatMessageVo.class);
                // TODO: 后端需要传递消息时间
                Date date = new Date();
                message.setGmtCreate(date);
                message.setGmtModify(date);
                MessageUtils.cache(message.getFrom(), message);
            }

            @Override
            public void onOpen(@NonNull WebSocket webSocket, @NonNull Response response) {
                super.onOpen(webSocket, response);
                MessageUtils.setSender(webSocket);
            }
        });

        // 聊天在线状态
        Api.newWebSocket(Apis.CHAT_SYS_MSG, new WebSocketListener() {
            @Override
            public void onClosed(@NonNull WebSocket webSocket, int code, @NonNull String reason) {
                super.onClosed(webSocket, code, reason);
            }

            @Override
            public void onFailure(@NonNull WebSocket webSocket, @NonNull Throwable t, @Nullable Response response) {
                super.onFailure(webSocket, t, response);
            }

            @Override
            public void onMessage(@NonNull WebSocket webSocket, @NonNull String text) {
                super.onMessage(webSocket, text);
            }

            @Override
            public void onOpen(@NonNull WebSocket webSocket, @NonNull Response response) {
                super.onOpen(webSocket, response);
            }
        });
    }

    private void getFriendList() {
        Api.get(getContext(), Apis.FRIEND_LIST, new ArrayList<>(), new Api.ApiCallback() {
            @Override
            public void onFailure(Context context, Call call, IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }

            @Override
            public void onResponse(Context context, Call call, Response response) throws IOException {
                String res = response.body().string();
                FriendListResp resp = JSON.parseObject(res, FriendListResp.class);
                if (resp != null && resp.getCode().equals(ApiStatusCode.OK)) {
                    List<FriendItemVo> list = resp.getData();
                    mAdapter.flushData(list);
                    getActivity().runOnUiThread(() -> mRecyclerView.scrollToPosition(0));
                } else {
                    reload();
                }
                mSmartRefreshLayout.finishRefresh(true);
            }
        });
    }
}